package com.musemun.config.filter;

import com.alibaba.fastjson.JSON;
import com.musemun.common.CommonResult;
import com.musemun.contants.ReturnType;
import com.musemun.exception.MyDefineException;
import com.musemun.pojo.Employee;
import com.musemun.pojo.EmployeeRepository;
import com.musemun.util.JwtTokenUtil;
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpExchange;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
//import javax.persistence.Cacheable;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *          自定义token访问Filter
 *</p>
 * @author winner
 * @date 2020/5/7
 */


public class TokenValidateFilter extends OncePerRequestFilter {
        Logger log=LoggerFactory.getLogger(TokenValidateFilter.class);

    private EmployeeRepository employeeRepository= new EmployeeRepository();

    /**
     *     token认证filter逻辑函数
     *
     * @param request 请求request
     * @param response 返回的报文
     * @param filterChain  filter链
     * @return void
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        String token= request.getHeader("token");  //url中取出token

        SecurityContext context = SecurityContextHolder.getContext();
        if(!StringUtils.isEmpty(token)){
            String username = JwtTokenUtil.getUsernameFromToken(token);

            if(JwtTokenUtil.canTokenBeRefreshed(token)){
                //判断token是否过期，过期则刷新token
                token=JwtTokenUtil.refreshToken(token);
            }

            //            //从缓存中查询登入用户，可用redis提高性能
            Employee employee = employeeRepository.findByUsername(username);
            if(employee==null){
                ReturnType.returnJson(response);
                response.getWriter().write(JSON.toJSONString(new CommonResult<String>(500, "用户已被注销请重新登入")));
                response.flushBuffer();
            }


            if(JwtTokenUtil.validateToken(token,employee)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null,employee.getAuthorities());
                //设置连接的远程地址
                usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                //设置用户登录状态
                context.setAuthentication(usernamePasswordAuthenticationToken);
                log.info("token认证成功");
            }

        }
        filterChain.doFilter(request,response);

    }

}
